//
//  AppDelegate.m
//  KissHealth
//
//  Created by Mark on 2017/1/9.
//  Copyright © 2017年 Mark. All rights reserved.
//

#import "AppDelegate.h"
#import "KHTabBarViewController.h"
#import "KHWelcomeVC.h"
#import "Reachability.h"
#import "KHLoginVC.h"
#import "KHCustomTool.h"
#import "KHCommentVC.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#import "EBForeNotification.h"

#import "AppDelegate+XGPush.h"

@interface AppDelegate ()<JPUSHRegisterDelegate>


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 1.创建窗口
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    
    // 2.设置根控制器
    [self switchRootViewController];
    
    // 3.显示窗口
    [self.window makeKeyAndVisible];
    
    //监听网络改变
    [self observerNetWorkChange];
    
    //初始化APNs代码
    [self configXGPushWithLaunchingOptions:launchOptions];

    
    return YES;
}

#pragma mark - privite
- (void)switchRootViewController {
    
    KHLoginVC *loginVC = [[KHLoginVC alloc]initWithURL:kLoginURLString];
    self.window.rootViewController = loginVC;
    
    /**
    NSString *key = @"CFBundleShortVersionString";
    // 上一次的使用版本（存储在沙盒中的版本号）
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    // 当前软件的版本号（从Info.plist中获得）
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    
    if ([currentVersion isEqualToString:lastVersion]) { // 版本号相同：这次打开和上次打开的是同一个版本
        KHLoginVC *loginVC = [[KHLoginVC alloc]initWithURL:kLoginURLString];
        self.window.rootViewController = loginVC;
    } else { // 这次打开的版本和上一次不一样，显示新特性
        self.window.rootViewController = [[KHWelcomeVC alloc] init];
        // 将当前的版本号存进沙盒
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }*/
}

- (void)observerNetWorkChange{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
    
}
- (void)networkStateChange{
    
    if ([self.conn currentReachabilityStatus] == NotReachable) {
        [SVProgressHUD showErrorWithStatus:@"网络不给力请检查网络"];
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        
    } else if ([self.conn currentReachabilityStatus] == ReachableViaWiFi) {
        
    } else {
        
    }
}



- (void)dealloc
{
    [self.conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self setXGApplicationBageNumber:0];
    
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#pragma mark- JPUSHRegisterDelegate
#warning todo mark - 对消息进行处理

// iOS 10 Support 处于前台时接收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];

    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    //处于前台处理接受到通知
    // 取得 APNs 标准信息内容
//    UNNotificationRequest *request = notification.request; // 收到推送的请求
//    UNNotificationContent *content = request.content; // 收到推送的消息内容
//    NSNumber *badge = content.badge;  // 推送消息的角标
//    NSString *body = content.body;    // 推送消息体
//    UNNotificationSound *sound = content.sound;  // 推送消息的声音
//    NSString *subtitle = content.subtitle;  // 推送消息的副标题
//    NSString *title = content.title;  // 推送消息的标题

#warning todo 确定userInfo 信息
    [KHCustomTool handlePushMessage:userInfo];
    
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}


// iOS 10 Support 点击处理事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    //处于后台处理接受到通知
    // 取得 APNs 标准信息内容
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge.intValue];
    [JPUSHService setBadge:badge.intValue];
    
#warning todo 确定userInfo 信息 
    //处理推送信息
    [KHCustomTool handlePushMessage:userInfo];
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    NSLog(@"[XGDemo] userinfo %@", userInfo);
    [self reportXGNotificationInfo:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}



@end
